//四、手写实现MyPromise源码
//要求：尽可能还原Promise中的每一个API，并通过注释的方式描述思路和原理。

//*****实现MyPromise源码：*****
//状态
const PENDING = 'pending'  //等待
const FULFILLED = 'fulfilled'  //成功
const REJECTED = 'rejected'  //失败

class MyPromise {
    constructor(executor) {
        try {
            executor(this.resolve, this.reject)
        } catch (error) {
            this.reject(error)
        }
    }
    //***实例/成员属性***
    //Promise状态
    status = PENDING
    //成功之后的值
    value = undefined
    //失败后的原因
    reason = undefined
    //成功回调
    successCallback = []
    //失败回调
    failCallback = []
    //***实例/成员方法***
    resolve = value => {
        //如果状态不是等待，阻止程序向下执行
        if (this.status !== PENDING) return
        //将状态更改为成功
        this.status = FULFILLED
        //保存成功后的值
        this.value = value
        //判断成功回调是否存在，如果存在，则调用
        while (this.successCallback.length) this.successCallback.shift()()
    }
    reject = reason => {
        //如果状态不是等待，阻止程序向下执行
        if (this.status !== PENDING) return
        //将状态更改为失败
        this.status = REJECTED
        //保存失败后的原因
        this.reason = reason
        //判断失败回调是否存在，如果存在，则调用
        while (this.failCallback.length) this.failCallback.shift()()
    }
    then(successCallback, failCallback) {
        successCallback = successCallback ? successCallback : value => value
        failCallback = failCallback ? failCallback : reason => { throw reason }
        const promise2 = new MyPromise((resolve, reject) => {
            //判断状态
            if (this.status === FULFILLED) {
                setTimeout(() => {
                    try {
                        const result = successCallback(this.value)
                        resolvePromise(promise2, result, resolve, reject)
                    } catch (error) {
                        reject(error)
                    }
                }, 0)
            } else if (this.status === REJECTED) {
                setTimeout(() => {
                    try {
                        const result = failCallback(this.reason)
                        resolvePromise(promise2, result, resolve, reject)
                    } catch (error) {
                        reject(error)
                    }
                }, 0)
            } else {
                //当前状态为等待状态，需要将成功回调存储起来
                this.successCallback.push(() => {
                    setTimeout(() => {
                        try {
                            const result = successCallback(this.value)
                            resolvePromise(promise2, result, resolve, reject)
                        } catch (error) {
                            reject(error)
                        }
                    }, 0)
                })
                //当前状态为等待状态，需要将失败回调存储起来
                this.failCallback.push(() => {
                    setTimeout(() => {
                        try {
                            const result = failCallback(this.reason)
                            resolvePromise(promise2, result, resolve, reject)
                        } catch (error) {
                            reject(error)
                        }
                    }, 0)
                })
            }
        })
        return promise2
    }
    finally(callback) {
        return this.then(value => {
            return MyPromise.resolve(callback()).then(() => value)
        }, reason => {
            return MyPromise.resolve(callback()).then(() => { throw reason })
        })
    }
    catch(failCallback) {
        return this.then(undefined, failCallback)
    }
    //***静态方法***
    static all(array) {
        let result = []
        //for循环时一瞬间就执行完成的，但是在for循环中存在异步操作，需要使用计数器统计数组中内容是否所有都执行完成
        //即需要等待所有异步操作完成之后，才能调用resolve去结束all方法的状态
        let index = 0
        return new MyPromise((resolve, reject) => {
            function addData(key, value) {
                result[key] = value
                index++;
                if (index === array.length) {
                    resolve(result)
                }
            }
            for (let i = 0; i < array.length; i++) {
                const current = array[i]
                if (current instanceof MyPromise) {
                    //promise对象
                    current.then(value => addData(i, value), reason => reject(reason))
                } else {
                    //普通值
                    addData(i, current)
                }
            }
        })
    }
    static resolve(value) {
        if (value instanceof MyPromise) return value;
        return new MyPromise(resolve => resolve(value))
    }
}

/***resolvePromise
 * 判断result的值是普通值还是promise对象
 * 如果是普通值，直接调用resolve
 * 如果是promise对象，查看promise对象返回的结果
 * 再根据promise对象返回的结果，决定调用resolve还是调用reject
 */
function resolvePromise(promise2, result, resolve, reject) {
    if (promise2 === result) {
        return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
    }
    if (result instanceof MyPromise) {
        //promise对象
        result.then(resolve, reject)
    } else {
        //普通值
        resolve(result)
    }
}
// module.exports = MyPromise

//*****测试*****
function p2() {
    return new MyPromise((resolve, reject) => {
        // resolve('p2 resolve')
        reject('p2 reject')
    })
}

p2().then(value => console.log(value)).catch(reason => console.log(reason))
//p2 reject